package controller

import (
	"fmt"
	"gin-shop-admin/common"
	"gin-shop-admin/middleware"
	"gin-shop-admin/models"
	"gin-shop-admin/repository"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"reflect"
	"time"
)

func RegisterHandler(c *gin.Context) {
	mail := c.DefaultQuery("mail", "")
	password := c.DefaultQuery("password", "")
	if mail != "" && password != "" {
		fmt.Println(mail, password)
		c.JSON(http.StatusOK, gin.H{
			"msg": "success",
		})
	} else {
		c.JSON(http.StatusOK, gin.H{
			"msg": "failed",
		})
	}
}

func LoginHandler(c *gin.Context) {
	name, NameOk := c.GetPostForm("name")
	password, PwdOk := c.GetPostForm("password")
	if !NameOk || !PwdOk {
		log.Println(name, password, reflect.TypeOf(password))
		c.JSON(201, "用户名或密码获取错误！")
	} else {
		if name == "zhangyafei" && password == "123456" {
			c.JSON(http.StatusOK, "success")
		} else {
			c.JSON(202, "用户名或密码不正确！")
		}
	}
}

// LoginResult 登录结果结构
type LoginResult struct {
	Token string `json:"token"`
	models.Manager
}


func BackendLogin(c *gin.Context)  {
	username, NameOk := c.GetPostForm("username")
	password, PwdOk := c.GetPostForm("password")
	if !NameOk || !PwdOk {
		c.JSON(201, gin.H{"msg": "用户名或密码获取错误","data": nil})
		return
	}
	manager, msg, isPass := repository.LoginCheckManger(username, password)
	if !isPass {
		c.JSON(202, gin.H{
			"msg":msg,
			"data":nil,
		})
	}else {
		msg, data, ok := generateToken(c, manager)
		if !ok {
			c.JSON(203, gin.H{"msg": msg, "data": nil})
		}else {
			c.JSON(http.StatusOK, gin.H{"msg":msg, "data": data})
		}
	}
	return
}

// 生成令牌
func generateToken(c *gin.Context, user models.Manager) (msg string, data LoginResult, ok bool) {
	j := &middleware.JWT{
		[]byte("newtrekWang"),
	}
	claims := middleware.CustomClaims{
		user.Id,
		user.Username,
		user.Mobile,
		user.Email,
		jwt.StandardClaims{
			NotBefore: int64(time.Now().Unix() - 1000), // 签名生效时间
			ExpiresAt: int64(time.Now().Unix() + 3600), // 过期时间 一小时
			Issuer:    "zhangyafei",                    //签名的发行者
		},
	}
	token, err := j.CreateToken(claims)
	if err != nil {
		log.Println(err)
		return "创建token失败", data, false
	} else {
		data = LoginResult{Manager: user, Token: token}
		return "登录成功！", data, true
	}
}

func Upload(c *gin.Context)  {
	file, _ := c.FormFile("file")
	uuid_string := common.NewUUID()
	filepath := "static/upload/goods/"+uuid_string + ".png"
	if err := c.SaveUploadedFile(file, filepath); err == nil {
		c.JSON(200, gin.H{"msg": "上传成功", "status": 200, "data": map[string]string{"tmp_path": "/" + filepath}})
	}
	//c.JSON(201, gin.H{"msg": err, "status": 201, "data": nil})
	return
}